﻿<?php

/* security */
$token   = '7246353147ef3886dd1b06dd5bf46906';
$project = '/www/wwwroot/support-ticket/server';
//ip地址为gitlab服务器请求地址
$access_ip = [];
/* get user token and ip address */
$client_token = isset($_SERVER['HTTP_X_GITEE_TOKEN']) ? $_SERVER['HTTP_X_GITEE_TOKEN'] : '';
$client_ip    = $_SERVER['REMOTE_ADDR'];
//查询服务器运行的php-fpm用户和文件所属权限是否一致
// print_r($_SERVER);
//文件记录日志
/* create open log */
$fs = fopen($project.'/storage/logs/webhook.log', 'a');
fwrite($fs, '===================================start====================================' . PHP_EOL);
fwrite($fs, 'Request on [' . date("Y-m-d H:i:s") . '] from [' . $client_ip . ']' . PHP_EOL);
/* test token */
if ($client_token !== $token) {
    echo "error 403";
    fwrite($fs, "Invalid token [{$client_token}]" . PHP_EOL);
    exit(0);
}
/* test ip*/
// if ( ! in_array($client_ip, $access_ip))
// {
// echo "error 503";
// fwrite($fs, "Invalid ip [{$client_ip}]".PHP_EOL);
// exit(0);
// }
/* get json data */
$json = file_get_contents('php://input');
$data = json_decode($json, true);
/* get branch */
$branch              = $data["ref"];
$total_commits_count = $data["total_commits_count"];
// $pushType = $data['object_kind'];
fwrite($fs, '=======================================================================' . PHP_EOL);
/* if you need get full json input */
// fwrite($fs, 'DATA: '.print_r($data, true).PHP_EOL);
/* branch filter */
if ($branch === 'refs/heads/master' && $total_commits_count > 0) {
    /* if master branch*/
    fwrite($fs, 'BRANCH: ' . print_r($branch, true) . PHP_EOL);
    fwrite($fs, '=======================================================================' . PHP_EOL);
    /* then pull master */
    // $result = shell_exec("cd {$project} && git pull 2>&1");
    $result = shell_exec("cd {$project} && git pull 2>&1");
    fwrite($fs, 'RESULT: ' . $result . PHP_EOL);
    fwrite($fs, '===================================end====================================' . PHP_EOL);
    $fs and fclose($fs);

    echo "success";
}
